package com.yzr.common.thread;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * cas中的ABA问题，以记录版本号形式实现
 *
 * @author YzrAdmin
 * @date new Date()
 */
public class AtomicStampedReferenceTest {

    private static class Demo {

        private String name;
        private Integer age;


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Demo{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    static Demo demo = new Demo();
    public static AtomicStampedReference<Demo> reference = new AtomicStampedReference<>(demo, 1);

    public static void main(String[] args) {
        demo.setName("1");
        boolean b = reference.compareAndSet(demo, demo, 1, 2);
        Demo demo1 = AtomicStampedReferenceTest.reference.getReference();
        String name = demo1.getName();
        System.out.println(name);
        boolean b1 = reference.compareAndSet(demo, demo, 2, 3);
        System.out.println(b1);
        System.out.println(demo1.getName());
    }
}
